const api = require('../../utils/api');

Page({
  data: {
    mealId: null,
    loading: true,
    mealTypes: ['早餐', '午餐', '晚餐', '加餐'],
    mealTypeIndex: 0,
    mealTime: '12:00',
    mealDate: '',
    foods: [],
    totalCalories: 0,
    totalCarbs: 0,
    totalProtein: 0,
    totalFat: 0,
    showFoodSearch: false,
    searchKeyword: '',
    searchResults: [],
    searching: false,
    
    // 食物详情和份量选择相关
    showFoodDetail: false,
    currentFood: null,
    selectedQuantity: 1,
    selectedUnitIndex: 0,
    unitOptions: ['份', '克', '个', '杯', '勺'],
    adjustedNutrition: {}
  },

  onLoad(options) {
    // 获取餐食ID
    const mealId = options.id;
    
    if (!mealId) {
      wx.showToast({
        title: '无效的餐食ID',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
    
    this.setData({ mealId });
    
    // 加载餐食数据
    this.loadMealData(mealId);
  },
  
  // 加载餐食数据
  async loadMealData(mealId) {
    this.setData({ loading: true });
    
    try {
      const result = await api.diet.getMealById(mealId);
      
      if (result && result.success) {
        const meal = result.data;
        
        // 计算餐食类型索引
        const mealTypeIndex = this.data.mealTypes.indexOf(meal.mealType);
        
        // 格式化日期显示
        const dateObj = new Date(meal.date);
        const formattedDate = `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}-${String(dateObj.getDate()).padStart(2, '0')}`;
        
        // 处理食物数据，保留原始营养值
        const processedFoods = (meal.foods || []).map(food => {
          // 判断当前食物的营养值是否正常 - 添加额外检查
          let isNutritionValid = true;
          const foodCalories = parseFloat(food.calories) || 0;
          
          // 检查是否有异常高的营养值 (超过2000卡路里/100g)
          if (foodCalories > 2000 && food.unit === '份') {
            console.warn(`检测到异常高的卡路里: ${food.name} - ${foodCalories}卡路里`);
            isNutritionValid = false;
          }
          
          // 尝试从food_info获取原始营养值
          let originalCalories, originalCarbs, originalProtein, originalFat;
          
          if (food.food_info) {
            // 如果有food_info字段，直接使用它的值
            originalCalories = parseFloat(food.food_info.originalCalories) || 0;
            originalCarbs = parseFloat(food.food_info.originalCarbs) || 0;
            originalProtein = parseFloat(food.food_info.originalProtein) || 0;
            originalFat = parseFloat(food.food_info.originalFat) || 0;
          } else if (food.originalCalories !== undefined) {
            // 如果有originalXXX字段，直接使用
            originalCalories = parseFloat(food.originalCalories) || 0;
            originalCarbs = parseFloat(food.originalCarbs) || 0;
            originalProtein = parseFloat(food.originalProtein) || 0;
            originalFat = parseFloat(food.originalFat) || 0;
          } else if (isNutritionValid) {
            // 如果营养值正常，且没有原始值，则根据单位和数量推算
            
            // 计算等效克数
            let gramsEquivalent = 0;
            if (food.unit === '克') {
              gramsEquivalent = parseFloat(food.quantity) || 0;
            } else if (food.unit === '份') {
              gramsEquivalent = 100; // 一份默认为100g
            } else if (food.unit === '个') {
              if (food.category === '水果类') {
                gramsEquivalent = 150; // 一个水果约150g
              } else {
                gramsEquivalent = 100; // 其他食物一个约100g
              }
            } else {
              gramsEquivalent = 100; // 默认100g
            }
            
            // 根据等效克数和当前营养值反推100g的原始营养值
            const ratio = 100 / gramsEquivalent;
            originalCalories = (parseFloat(food.calories) || 0) * ratio;
            originalCarbs = (parseFloat(food.carbs) || 0) * ratio;
            originalProtein = (parseFloat(food.protein) || 0) * ratio;
            originalFat = (parseFloat(food.fat) || 0) * ratio;
          } else {
            // 如果营养值异常，使用更合理的默认值
            // 对于一份鸡肉松，估计约450卡路里/100g
            if (food.name.includes('肉松')) {
              originalCalories = 450;
              originalCarbs = 10;
              originalProtein = 40;
              originalFat = 25;
            } else {
              // 其他未知食物的默认值
              originalCalories = 200;
              originalCarbs = 20;
              originalProtein = 10;
              originalFat = 5;
            }
          }
          
          // 验证计算出的原始值是否合理
          if (originalCalories > 2000) {
            console.warn(`计算出的原始卡路里值过高，进行修正: ${originalCalories} -> 450`);
            originalCalories = 450; // 使用合理的默认值替代
            originalCarbs = 10;
            originalProtein = 40;
            originalFat = 25;
          }
          
          // 计算当前份量下的实际营养值
          let displayCalories, displayCarbs, displayProtein, displayFat;
          
          // 计算等效克数
          let gramsEquivalent = 0;
          if (food.unit === '克') {
            gramsEquivalent = parseFloat(food.quantity) || 0;
          } else if (food.unit === '份') {
            gramsEquivalent = 100 * (parseFloat(food.quantity) || 1); // 一份默认为100g
          } else if (food.unit === '个') {
            if (food.category === '水果类') {
              gramsEquivalent = 150 * (parseFloat(food.quantity) || 1); // 一个水果约150g
            } else {
              gramsEquivalent = 100 * (parseFloat(food.quantity) || 1); // 其他食物一个约100g
            }
          } else {
            gramsEquivalent = 100 * (parseFloat(food.quantity) || 1); // 默认100g
          }
          
          // 根据等效克数计算实际营养值
          const ratio = gramsEquivalent / 100;
          displayCalories = originalCalories * ratio;
          displayCarbs = originalCarbs * ratio;
          displayProtein = originalProtein * ratio;
          displayFat = originalFat * ratio;
          
          return {
            ...food,
            id: food._id || food.foodId || `temp-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
            name: food.name || '未命名食物',
            // 使用当前份量的营养值
            calories: parseFloat(food.calories) || 0,
            carbs: parseFloat(food.carbs) || 0,
            protein: parseFloat(food.protein) || 0,
            fat: parseFloat(food.fat) || 0,
            // 计算的显示值
            displayCalories: Math.round(displayCalories),
            displayCarbs: Math.round(displayCarbs * 10) / 10,
            displayProtein: Math.round(displayProtein * 10) / 10,
            displayFat: Math.round(displayFat * 10) / 10,
            // 保存100g时的原始营养值
            originalCalories,
            originalCarbs,
            originalProtein,
            originalFat,
            // 其他必要字段
            quantity: parseFloat(food.quantity) || 1,
            unit: food.unit || '克',
            category: food.category || '其他',
            baseAmount: 100, // 统一使用100作为基准量
            baseUnit: '克',
            // 添加已处理标记
            processed: true
          };
        });
        
        // 设置总营养值 - 重新计算，不使用传入的值
        let totalCalories = 0, totalCarbs = 0, totalProtein = 0, totalFat = 0;
        
        processedFoods.forEach(food => {
          totalCalories += food.displayCalories || 0;
          totalCarbs += food.displayCarbs || 0;
          totalProtein += food.displayProtein || 0;
          totalFat += food.displayFat || 0;
        });
        
        this.setData({
          mealTypeIndex: mealTypeIndex !== -1 ? mealTypeIndex : 0,
          mealTime: meal.time,
          mealDate: formattedDate,
          foods: processedFoods,
          totalCalories: Math.round(totalCalories),
          totalCarbs: Math.round(totalCarbs * 10) / 10,
          totalProtein: Math.round(totalProtein * 10) / 10,
          totalFat: Math.round(totalFat * 10) / 10,
          loading: false
        });
      } else {
        wx.showToast({
          title: '加载失败：无法获取餐食数据',
          icon: 'none'
        });
        this.setData({ loading: false });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    } catch (error) {
      console.error('加载餐食详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 更新营养总计 - 专用于食物分量变更时调用
  updateNutritionTotals() {
    const foods = this.data.foods;
    let totalCalories = 0, totalCarbs = 0, totalProtein = 0, totalFat = 0;
    
    // 格式化foods数组中的营养值，考虑单位和份量
    const formattedFoods = foods.map(food => {
      // 深拷贝避免直接修改原始数据
      const formattedFood = { ...food };
      
      // 获取单位和数量
      const unit = food.unit;
      const quantity = parseFloat(food.quantity) || 1;
      
      // 计算为克的等效值
      let gramsEquivalent = 0;
      
      // 根据单位类型计算克数
      if (unit === '克') {
        gramsEquivalent = quantity;
      } else if (unit === '份') {
        // 一份默认为100g，除非有特殊定义
        gramsEquivalent = food.portionWeight ? quantity * food.portionWeight : quantity * 100;
      } else if (unit === '个') {
        if (food.category === '水果类') {
          gramsEquivalent = quantity * 150; // 1个水果约150g
        } else {
          gramsEquivalent = quantity * 100; // 其他默认100g
        }
      } else if (unit === '杯') {
        if (food.category === '蔬菜类') {
          gramsEquivalent = quantity * 200; // 1杯蔬菜约200g
        } else {
          gramsEquivalent = quantity * 150; // 其他默认150g
        }
      } else if (unit === '勺') {
        gramsEquivalent = quantity * 10; // 1勺约10g
      } else if (food.commonPortions && food.commonPortions.length > 0 && food.commonPortions[0].gramWeight) {
        gramsEquivalent = quantity * food.commonPortions[0].gramWeight;
      } else {
        gramsEquivalent = quantity * 100; // 默认100g
      }
      
      // 计算比例 (当前克数/100克)
      const ratio = gramsEquivalent / 100;
      
      // 使用原始营养值（100g时的值）进行计算
      const originalCalories = formattedFood.originalCalories;
      const originalCarbs = formattedFood.originalCarbs;
      const originalProtein = formattedFood.originalProtein;
      const originalFat = formattedFood.originalFat;
      
      // 预计算并格式化营养值
      formattedFood.displayCalories = Math.round(originalCalories * ratio);
      formattedFood.displayCarbs = Math.round(originalCarbs * ratio * 10) / 10;
      formattedFood.displayProtein = Math.round(originalProtein * ratio * 10) / 10;
      formattedFood.displayFat = Math.round(originalFat * ratio * 10) / 10;
      
      console.log(`食物: ${food.name}, 单位: ${unit}, 数量: ${quantity}, 等效克数: ${gramsEquivalent}g, 比例: ${ratio}`);
      console.log(`原始卡路里: ${originalCalories}, 计算后: ${formattedFood.displayCalories}`);
      
      // 累加到总计
      totalCalories += formattedFood.displayCalories;
      totalCarbs += formattedFood.displayCarbs;
      totalProtein += formattedFood.displayProtein;
      totalFat += formattedFood.displayFat;
      
      return formattedFood;
    });
    
    this.setData({
      foods: formattedFoods,
      totalCalories: Math.round(totalCalories),
      totalCarbs: Math.round(totalCarbs * 10) / 10,
      totalProtein: Math.round(totalProtein * 10) / 10,
      totalFat: Math.round(totalFat * 10) / 10
    });
  },
  
  // 餐食类型改变
  onMealTypeChange(e) {
    this.setData({
      mealTypeIndex: parseInt(e.detail.value)
    });
  },

  // 日期改变
  onDateChange(e) {
    this.setData({
      mealDate: e.detail.value
    });
  },

  // 时间改变
  onTimeChange(e) {
    this.setData({
      mealTime: e.detail.value
    });
  },

  // 显示食物搜索
  showFoodSearch() {
    this.setData({
      showFoodSearch: true,
      searchKeyword: '',
      searchResults: []
    });
  },

  // 隐藏食物搜索
  hideFoodSearch() {
    this.setData({
      showFoodSearch: false
    });
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
    
    // 如果输入框为空，清空搜索结果
    if (!e.detail.value.trim()) {
      this.setData({
        searchResults: []
      });
    } else {
      // 当输入内容变化时自动搜索
      this.searchFood();
    }
  },
  
  // 搜索食物 - 移植自dietAdd页面
  async searchFood() {
    const query = this.data.searchKeyword.trim();
    if (!query) return;
    
    this.setData({ searching: true });
    
    try {
      // 优先使用天行API搜索
      const result = await api.diet.searchTianapiFood(
        query,
        0,  // 按名称搜索
        10  // 返回10条结果
      );
      
      if (result && result.success && result.data && result.data.length > 0) {
        this.setData({
          searchResults: result.data,
          searching: false
        });
      } else {
        // 如果天行API没有结果，尝试本地数据库搜索
        const localResult = await api.diet.searchFoods(query);
        
        if (localResult && localResult.success) {
          this.setData({
            searchResults: localResult.data,
            searching: false
          });
        } else {
          this.setData({
            searchResults: [],
            searching: false
          });
          
          wx.showToast({
            title: '未找到匹配的食物',
            icon: 'none'
          });
        }
      }
    } catch (error) {
      console.error('搜索食物失败:', error);
      this.setData({ searching: false });
      wx.showToast({
        title: '搜索失败',
        icon: 'none'
      });
    }
  },
  
  // 显示食物详情
  showFoodDetail(e) {
    const food = e.currentTarget.dataset.food;
    
    this.setData({
      showFoodDetail: true,
      currentFood: food,
      selectedQuantity: 1,
      selectedUnitIndex: 0, // 默认为"份"
      adjustedNutrition: this.calculateAdjustedNutrition(food, 1, this.data.unitOptions[0])
    });
  },
  
  // 隐藏食物详情
  hideFoodDetail() {
    this.setData({
      showFoodDetail: false,
      currentFood: null,
      selectedQuantity: 1,
      selectedUnitIndex: 0,
      adjustedNutrition: {}
    });
  },
  
  // 份量输入改变
  onQuantityInput(e) {
    const value = e.detail.value;
    const quantity = parseFloat(value) || 1;
    
    if (quantity <= 0) {
      this.setData({ selectedQuantity: 1 });
      return;
    }
    
    const unit = this.data.unitOptions[this.data.selectedUnitIndex];
    const adjustedNutrition = this.calculateAdjustedNutrition(this.data.currentFood, quantity, unit);
    
    this.setData({
      selectedQuantity: quantity,
      adjustedNutrition
    });
  },
  
  // 单位选择改变
  onUnitChange(e) {
    const unitIndex = parseInt(e.detail.value);
    const unit = this.data.unitOptions[unitIndex];
    const adjustedNutrition = this.calculateAdjustedNutrition(this.data.currentFood, this.data.selectedQuantity, unit);
    
    this.setData({
      selectedUnitIndex: unitIndex,
      adjustedNutrition
    });
  },
  
  // 计算调整后的营养值
  calculateAdjustedNutrition(food, quantity, unit) {
    if (!food) return {};
    
    const baseAmount = 100; // 统一使用100克作为基准量
    quantity = parseFloat(quantity) || 1;
    
    // 计算为克的等效值
    let gramsEquivalent = 0;
    
    // 根据单位类型计算克数
    if (unit === '克') {
      gramsEquivalent = quantity;
    } else if (unit === '份') {
      // 一份默认为100g，除非有特殊定义
      gramsEquivalent = food.portionWeight ? quantity * food.portionWeight : quantity * 100;
    } else if (unit === '个') {
      if (food.category === '水果类') {
        gramsEquivalent = quantity * 150; // 1个水果约150g
      } else {
        gramsEquivalent = quantity * 100; // 其他默认100g
      }
    } else if (unit === '杯') {
      if (food.category === '蔬菜类') {
        gramsEquivalent = quantity * 200; // 1杯蔬菜约200g
      } else {
        gramsEquivalent = quantity * 150; // 其他默认150g
      }
    } else if (unit === '勺') {
      gramsEquivalent = quantity * 10; // 1勺约10g
    } else if (food.commonPortions && food.commonPortions.length > 0 && food.commonPortions[0].gramWeight) {
      gramsEquivalent = quantity * food.commonPortions[0].gramWeight;
    } else {
      gramsEquivalent = quantity * 100; // 默认100g
    }
    
    // 计算比例 (当前克数/100克)
    const ratio = gramsEquivalent / 100;
    
    console.log(`食物: ${food.name}, 单位: ${unit}, 数量: ${quantity}, 等效克数: ${gramsEquivalent}g, 比例: ${ratio}`);
    
    // 使用原始营养值（标准100g）计算
    const originalCalories = food.originalCalories || food.calories || 0;
    const originalCarbs = food.originalCarbs || food.carbs || 0;
    const originalProtein = food.originalProtein || food.protein || 0;
    const originalFat = food.originalFat || food.fat || 0;
    
    // 计算调整后的营养值
    const adjustedCalories = originalCalories * ratio;
    const adjustedCarbs = originalCarbs * ratio;
    const adjustedProtein = originalProtein * ratio;
    const adjustedFat = originalFat * ratio;
    
    return {
      calories: Math.round(adjustedCalories),
      carbs: Math.round(adjustedCarbs * 10) / 10,
      protein: Math.round(adjustedProtein * 10) / 10,
      fat: Math.round(adjustedFat * 10) / 10
    };
  },
  
  // 确认添加食物
  confirmAddFood() {
    const food = this.data.currentFood;
    if (!food) return;
    
    const quantity = this.data.selectedQuantity;
    const unitIndex = this.data.selectedUnitIndex;
    const unit = this.data.unitOptions[unitIndex];
    
    // 计算100g时的原始营养值
    let originalCalories, originalCarbs, originalProtein, originalFat;
    
    // 如果当前是完整的100g数据，直接使用
    if (food.quantity == 100 && food.unit === '克') {
      originalCalories = parseFloat(food.calories) || 0;
      originalCarbs = parseFloat(food.carbs) || 0;
      originalProtein = parseFloat(food.protein) || 0;
      originalFat = parseFloat(food.fat) || 0;
    } else {
      // 否则，直接使用传入的值（应已标准化为100g）
      originalCalories = parseFloat(food.calories) || 0;
      originalCarbs = parseFloat(food.carbs) || 0;
      originalProtein = parseFloat(food.protein) || 0;
      originalFat = parseFloat(food.fat) || 0;
    }
    
    // 创建一个新的食物对象，包含选择的份量信息和原始营养数据
    const newFood = {
      ...food,
      id: food._id || food.id || `temp-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
      quantity: quantity,
      unit: unit,
      // 计算当前份量下的营养值（显示值）
      displayCalories: this.data.adjustedNutrition.calories || 0,
      displayCarbs: this.data.adjustedNutrition.carbs || 0,
      displayProtein: this.data.adjustedNutrition.protein || 0,
      displayFat: this.data.adjustedNutrition.fat || 0,
      // 保存100g时的原始营养值
      originalCalories,
      originalCarbs,
      originalProtein,
      originalFat,
      // 确保必要字段存在
      name: food.name || '未命名食物',
      calories: parseFloat(food.calories) || 0,
      carbs: parseFloat(food.carbs) || 0,
      protein: parseFloat(food.protein) || 0,
      fat: parseFloat(food.fat) || 0,
      category: food.category || '其他',
      baseAmount: 100, // 统一使用100作为基准量
      baseUnit: '克',
      // 添加已处理标记
      processed: true
    };
    
    const foods = [...this.data.foods, newFood];
    
    this.setData({
      foods,
      showFoodDetail: false,
      showFoodSearch: false,
      currentFood: null
    });
    
    // 更新营养总计
    this.updateNutritionTotals();
    
    // 提示用户添加成功
    wx.showToast({
      title: '已添加到餐食',
      icon: 'success',
      duration: 1500
    });
    
    // 如果食物来源是天行API且没有_id，尝试保存到本地数据库
    if (food.source === 'tianapi' && !food._id) {
      this.saveFoodToDatabase(newFood);
    }
  },
  
  // 保存食物到数据库
  async saveFoodToDatabase(food) {
    try {
      // 准备完整的食物数据对象用于保存
      const foodDataToSave = {
        name: food.name,
        calories: food.calories,
        carbs: food.carbs || 0,
        protein: food.protein || 0,
        fat: food.fat || 0,
        fiber: food.fiber || 0,
        sugar: food.sugar || 0,
        category: food.category || '其他',
        source: 'tianapi',
        commonPortions: food.commonPortions || [{ description: '一份', gramWeight: 100 }],
        baseAmount: food.baseAmount || 100,
        baseUnit: food.baseUnit || '克'
      };
      
      // 保存食物到本地数据库
      const saveResult = await api.diet.saveTianapiFood(foodDataToSave);
      
      if (saveResult && saveResult.success) {
        console.log('食物已保存到本地数据库');
      }
    } catch (error) {
      console.error('保存食物到数据库失败:', error);
    }
  },
  
  // 从搜索结果添加食物
  addFood(e) {
    const food = e.currentTarget.dataset.food;
    this.showFoodDetail(e);
  },
  
  // 增加选择的数量
  increaseSelectedQuantity() {
    const quantity = parseFloat(this.data.selectedQuantity) + 1;
    const unit = this.data.unitOptions[this.data.selectedUnitIndex];
    const adjustedNutrition = this.calculateAdjustedNutrition(this.data.currentFood, quantity, unit);
    
    this.setData({
      selectedQuantity: quantity,
      adjustedNutrition
    });
  },
  
  // 减少选择的数量
  decreaseSelectedQuantity() {
    if (this.data.selectedQuantity <= 1) return;
    
    const quantity = parseFloat(this.data.selectedQuantity) - 1;
    const unit = this.data.unitOptions[this.data.selectedUnitIndex];
    const adjustedNutrition = this.calculateAdjustedNutrition(this.data.currentFood, quantity, unit);
    
    this.setData({
      selectedQuantity: quantity,
      adjustedNutrition
    });
  },

  // 增加食物数量 - 使用id来找食物
  increaseQuantity(e) {
    const id = e.currentTarget.dataset.id;
    const foods = [...this.data.foods];
    const index = foods.findIndex(item => item.id === id);
    
    if (index !== -1) {
      foods[index].quantity = parseFloat(foods[index].quantity || 1) + 1;
      this.setData({ foods });
      this.updateNutritionTotals();
    }
  },

  // 减少食物数量 - 使用id来找食物
  decreaseQuantity(e) {
    const id = e.currentTarget.dataset.id;
    const foods = [...this.data.foods];
    const index = foods.findIndex(item => item.id === id);
    
    if (index !== -1 && foods[index].quantity > 1) {
      foods[index].quantity = parseFloat(foods[index].quantity || 2) - 1;
      this.setData({ foods });
      this.updateNutritionTotals();
    }
  },

  // 删除食物 - 使用id来找食物
  deleteFood(e) {
    const id = e.currentTarget.dataset.id;
    const foods = this.data.foods.filter(item => item.id !== id);
    this.setData({ foods });
    this.updateNutritionTotals();
  },

  // 取消编辑
  cancelEdit() {
    wx.navigateBack();
  },

  // 保存餐食信息
  async saveMeal() {
    // 检查是否有食物
    if (this.data.foods.length === 0) {
      wx.showToast({
        title: '请添加至少一种食物',
        icon: 'none'
      });
      return;
    }
    
    // 准备要保存的数据
    const { mealId, mealTypeIndex, mealTypes, mealDate, mealTime, foods, totalCalories, totalCarbs, totalProtein, totalFat } = this.data;
    
    const mealData = {
      mealId, // 传递餐食ID进行更新
      mealType: mealTypes[mealTypeIndex],
      date: mealDate,
      time: mealTime,
      totalCalories,
      totalCarbs,
      totalProtein,
      totalFat,
      foods: foods.map(food => {
        // 准备食物数据，只使用显示值作为营养值
        const baseFood = {
          name: food.name,
          quantity: parseFloat(food.quantity) || 1,
          unit: food.unit || '份',
          // 使用显示值作为营养值，这是当前份量下实际的营养值
          calories: parseFloat(food.displayCalories) || 0,
          carbs: parseFloat(food.displayCarbs) || 0,
          protein: parseFloat(food.displayProtein) || 0,
          fat: parseFloat(food.displayFat) || 0,
          // 保存food_info信息用于标识食物
          category: food.category || '其他',
          baseAmount: 100,
          baseUnit: '克'
        };
        
        // 如果有foodId，添加引用
        if (food._id || food.foodId) {
          baseFood.foodId = food._id || food.foodId;
        }
        
        // 将原始营养值作为单独属性保存（后端应只用于计算，不应直接显示）
        baseFood.food_info = {
          originalCalories: parseFloat(food.originalCalories) || 0,
          originalCarbs: parseFloat(food.originalCarbs) || 0,
          originalProtein: parseFloat(food.originalProtein) || 0,
          originalFat: parseFloat(food.originalFat) || 0
        };
        
        return baseFood;
      })
    };
    
    console.log('保存的餐食数据:', mealData);
    
    try {
      wx.showLoading({ title: '保存中...' });
      
      // 从mealData中提取出mealId，其余作为餐食数据
      const { mealId, ...mealDataToSave } = mealData;
      const result = await api.diet.updateMeal(mealId, mealDataToSave);
      
      if (result && result.success) {
        wx.hideLoading();
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        
        // 获取页面栈
        const pages = getCurrentPages();
        // 获取上一个页面的实例
        if (pages.length > 1) {
          const prevPage = pages[pages.length - 2];
          // 如果上一页存在，直接设置刷新标记和调用刷新方法
          if (prevPage) {
            console.log('准备刷新上一页数据，上一页路径:', prevPage.route);
            
            // 设置数据需要刷新的标志
            prevPage.setData({
              needRefresh: true
            });
            
            // 直接调用刷新方法
            if (typeof prevPage.loadMealDetail === 'function') {
              try {
                prevPage.loadMealDetail(mealId);
                console.log('已直接调用上一页的loadMealDetail方法');
              } catch (e) {
                console.error('调用上一页刷新方法失败:', e);
              }
            }
          }
        }
        
        // 返回上一页，并将结果传回上一页
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          });
        }, 1500);
      } else {
        wx.hideLoading();
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('保存餐食失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  },

  // 保存按钮点击
  onSave() {
    this.saveMeal();
  }
}); 